import os  
import chardet  
import codecs  
  
def convert_file_to_utf8(file_path):  
    with open(file_path, 'rb') as f:  
        raw_data = f.read()  
        result = chardet.detect(raw_data)  
        encoding = result['encoding']  
          
        if encoding == 'GB2312':  
            try:  
                content = raw_data.decode('GB2312')  
                with codecs.open(file_path, 'w', 'utf-8') as output_file:  
                    output_file.write(content)  
                print(f"Converted {file_path} to UTF-8")  
            except Exception as e:  
                print(f"Error converting {file_path}: {e}")  
        else:  
            print(f"Skipped {file_path} (not GB2312)")  
  
def convert_directory_to_utf8(directory):  
    for root, dirs, files in os.walk(directory):  
        for file in files:  
            file_path = os.path.join(root, file)  
            convert_file_to_utf8(file_path)  
  
if __name__ == "__main__":  
    directory_to_convert = input("Enter the directory path to convert: ")  
    convert_directory_to_utf8(directory_to_convert)